package com.guomei.controller.curse;

import com.guomei.bean.CreateOrUpdateChannel;
import com.guomei.bean.curse.AuthorizeChannelCode;
import com.guomei.bean.curse.Channel;
import com.guomei.service.curse.ChannelService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 渠道控制器
 */
@RestController
@RequestMapping("/api1/channel")
@Slf4j
public class ChannelController {
    @Autowired
    private ChannelService channelService;

    /**
     * 获取渠道信息
     * @return 渠道列表
     */
    @PostMapping("/select")
    public Result<?> getAllChannels(@RequestBody Channel channel) {
        log.info("获取渠道信息");
        try {
            if (channel == null || channel.getPageNum() == null || channel.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (channel.getPageNum() <= 0 || channel.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return channelService.getByCondition(channel);
        } catch (Exception e) {
            log.info("获取渠道信息失败", e);
            return Result.fail("获取渠道信息失败");
        }
    }

    /**
     * 根据ID获取渠道详情
     * @param id 渠道ID
     * @return 渠道详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getChannelDetail(@PathVariable Long id) {
        log.info("获取渠道详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("渠道ID不能为空");
            }
            Channel channel = channelService.getById(id);
            if (channel == null) {
                return Result.fail("渠道不存在");
            }
            return Result.success(channel);
        } catch (Exception e) {
            log.info("获取渠道详情失败", e);
            return Result.fail("获取渠道详情失败");
        }
    }

    /**
     * 新增/修改渠道
     * @param createOrUpdateChannel 渠道信息
     * @return 新增结果
     */
    @PostMapping("/addOrUpdate")
    public Result<?> addChannel(@Valid @RequestBody CreateOrUpdateChannel createOrUpdateChannel, BindingResult result) {
        log.info("新增/修改渠道入参：{}", createOrUpdateChannel);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        Channel channel = new Channel();
        channel.setChannelCode(createOrUpdateChannel.getChannelCode());
        channel.setChannelName(createOrUpdateChannel.getChannelName());
        channel.setSortOrder(createOrUpdateChannel.getSortOrder());
        channel.setRemark(createOrUpdateChannel.getRemark());
        channel.setChannelSecret(createOrUpdateChannel.getChannelSecret());
        try {
            if (createOrUpdateChannel.getId() != null){
                channel.setId(createOrUpdateChannel.getId());
                channel.setStatus(createOrUpdateChannel.getStatus());
                boolean success = channelService.update(channel);
                return success ? Result.success("修改成功") : Result.fail("修改失败");
            } else {
                channel.setStatus((short) 1);
                boolean success = channelService.save(channel);
                return success ? Result.success("新增成功") : Result.fail("新增失败");
            }
        } catch (Exception e) {
            log.info("新增/修改渠道失败", e);
            return Result.error("新增/修改渠道失败");
        }
    }


    /**
     * 删除渠道
     * @param id 渠道ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteChannel(@PathVariable Long id) {
        log.info("删除渠道，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("渠道ID不能为空");
            }
            boolean success = channelService.removeById(id);
            return success ? Result.success("删除成功") : Result.fail("删除失败");
        } catch (Exception e) {
            log.info("删除渠道失败", e);
            return Result.fail("删除渠道失败");
        }
    }

    /**
     * 根据渠道编码查询
     * @param channelCode 渠道编码
     * @return 渠道信息
     */
    @GetMapping("/code/{channelCode}")
    public Result<?> getByChannelCode(@PathVariable String channelCode) {
        log.info("根据渠道编码查询，渠道编码：{}", channelCode);
        try {
            if (channelCode == null) {
                return Result.fail("渠道编码不能为空");
            }
            Channel channel = channelService.getByChannelCode(channelCode);
            if (channel == null) {
                return Result.fail("渠道不存在");
            }
            return Result.success(channel);
        } catch (Exception e) {
            log.info("根据渠道编码查询失败", e);
            return Result.fail("查询失败");
        }
    }

    /**
     * 根据状态查询渠道
     * @param status 状态
     * @return 渠道列表
     */
    @GetMapping("/status/{status}")
    public Result<?> getByStatus(@PathVariable Short status) {
        log.info("根据状态查询渠道，状态：{}", status);
        try {
            if (status == null) {
                return Result.fail("状态不能为空");
            }
            List<Channel> channels = channelService.getByStatus(status);
            return Result.success(channels);
        } catch (Exception e) {
            log.info("根据状态查询渠道失败", e);
            return Result.fail("查询失败");
        }
    }

    /**
     * 生成渠道密钥
     * @return 渠道密钥
     */
    @GetMapping("/generateSecret")
    public Result<?> generateChannelSecret() {
        log.info("生成渠道密钥");
        try {
            String secret = channelService.generateChannelSecret();
            return Result.success(secret);
        } catch (Exception e) {
            log.info("生成渠道密钥失败", e);
            return Result.fail("生成失败");
        }
    }

    /**
     * 验证渠道密钥
     * @param channelSecret 渠道密钥
     * @return 验证结果
     */
    @GetMapping("/validateSecret/{channelSecret}")
    public Result<?> validateChannelSecret(@PathVariable String channelSecret) {
        log.info("验证渠道密钥，密钥：{}", channelSecret);
        try {
            if (channelSecret == null) {
                return Result.fail("渠道密钥不能为空");
            }
            boolean isValid = channelService.validateChannelSecret(channelSecret);
            return Result.success(isValid);
        } catch (Exception e) {
            log.info("验证渠道密钥失败", e);
            return Result.fail("验证失败");
        }
    }
    /**
     * 授权渠道编码给用户
     * @param authorizeChannelCode 渠道信息
     * @return 返回
     */
    @PostMapping("/authorizeChannelCode")
    public Result<?> authorizeChannelCode(@Valid @RequestBody AuthorizeChannelCode authorizeChannelCode, BindingResult result) {
        log.info("授权渠道编码给用户入参：{}", authorizeChannelCode);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return channelService.authorizeChannelCode(authorizeChannelCode);
        } catch (Exception e) {
            log.info("新增/修改渠道失败", e);
            return Result.error("新增/修改渠道失败");
        }
    }


}
